const { reqWithSSL } = require('./util')
const { getServiceWithCondition } = require('./microservice')

async function getInstanceWithCondition(ip, appId = 'WiseCarCloud', serviceName, version) {
  const services = await getServiceWithCondition(ip, {
    cAppId: appId,
    cServiceName: serviceName,
    cVersion: version
  })
  return Promise.all(services.map(({ serviceId }) => getAllInstances(serviceId, ip)))
}

function getAllInstances(serviceId, ip, port = 30100) {
  // const url = `https://${ip}:${port}/v4/default/registry/instances?appId=WiseCarCloud&serviceName=user-manager&version=1.0.5`
  const url = `https://${ip}:${port}/v4/default/registry/microservices/${serviceId}/instances`
  return reqWithSSL(url, { 'X-ConsumerId': serviceId }).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data
  }).catch(err => {
    // handle err
    throw new Error(`获取所有的Instance失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

module.exports = { getAllInstances, getInstanceWithCondition }
